const app = getApp();

Page({
  data: {
    username: 'user1', // 默认用户账号
    password: '123456'
  },
  
  inputUsername(e) { this.setData({ username: e.detail.value }); },
  inputPassword(e) { this.setData({ password: e.detail.value }); },

  handleLogin() {
    const { username, password } = this.data;
    wx.showLoading({ title: '登录中' });
    
    app.request('/api/login', 'POST', { username, password }).then(res => {
      const { user, token } = res;
      app.globalData.userInfo = user;
      app.globalData.token = token;
      wx.setStorageSync('userInfo', user); // 存储身份信息
      
      app.initWebSocket(); // 成功登录后建立 WebSocket 连接

      wx.hideLoading();
      wx.showToast({ title: user.nickname + ' 登录成功', icon: 'success' });
      
      if (user.role === 'doctor') {
        wx.redirectTo({ url: '/pages/doctor/appointmentList/appointmentList' });
      } else {
        wx.redirectTo({ url: '/pages/user/doctorList/doctorList' });
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({ title: err, icon: 'none' });
    });
  }
});